/*
 * NetworkHelper.h
 *
 *  Created on: 2013年7月26日
 *      Author: sun
 */

#ifndef NETWORKHELPER_H_
#define NETWORKHELPER_H_

#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include "../common/common_define.h"
#include "Framework.h"
#include "IConnector.h"

namespace sdfs {

enum SocketStatus{CLOSED = 0, ESTABLISHED, LISTENING, CREATEFAILURE};

typedef struct _Socket{
	struct sockaddr_in	s_addr;
	SocketStatus		status;
	int					sockfd;
	bool				bBlock;
	bool				bKeepAlive;
	ServerConfig		*config;
}SocketBody;

class Socket :public IConnector{
private:
	Socket(int sockfd, SocketStatus status, bool isblock = true);

public:
	Socket(ServerConfig *conf, bool isBlock = true, bool isKeepalive = false);

	virtual ~Socket();

	int Connect();

	int DisConnect();

	Socket *Clone();

	int CreateListenSocket();

	int Read(void* buf, int size);

	int Write(const void *buf, int size);

	int SetNoBlock(bool flag=true);

	int GetDescriptor();

	SocketStatus GetStatus();

	const char *GetServerName();

	static Socket* BuildConnectedSocket(int fd, bool isBlock = true);

private:
	SocketBody*	m_sBody;

};

} /* namespace sdfs */
#endif /* NETWORKHELPER_H_ */
